'use strict';
/**
 * api服务 
 * 版本   0.0.1
 * 方法   说明  调用接口的基类
 * get    get请求
 * post   post请求
 */
import excludeURLs from '../excludeURLs.js';
var Promise = require('./es6-promise.min');
var config = require('../config.js');
var json2Form = require('./json2Form.js');



//封装接口请求 
// method, api_url, data, header, errorInfo
let request = function (request_data) {
  return new Promise(function (resolve, reject) {
   
    wx.request({
      url: request_data.api_url ,
      data: request_data.data || {},
      method: request_data.method || "GET",
      header: request_data.header || {},
      dataType: "json",
      success(res) {
       
        // res.statusCode == 200 && 
        if (res.data.code == 0) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail(error) {
        console.error(request_data.method + ' 失败', request_data.api_url, request_data.data, error)
        reject(request_data.errorInfo || error);
      }
    })
  });
}

//基本授权路由
let isExclude = function (url) {
  return excludeURLs.indexOf(url) != -1
}


//引用该文件的对象
let minaApi = {
  _getToken() {
    return wx.getStorageSync("session:sso") || {};
  },
  _getRequestHeader(api_url) {
    var localAccessToken = minaApi._getToken();
    return {
      // 'content-type': 'application/json'
      'content-type': 'application/x-www-form-urlencoded',
    }
  },
  //get 请求 
  get(api_url, _data) {

    var parms = json2Form(_data);
    return request({
      method: "GET",
      api_url: config.api + api_url + (api_url.indexOf('?') != -1 ? "&" : "?") + parms,
      data: {},
      header: minaApi._getRequestHeader(api_url),
      dataType: 'json'
    });
  },
  //post 请求
  post(api_url, data) {
    return request({
      method: "POST",
      api_url: config.api + api_url,
      data: data,
      header: minaApi._getRequestHeader(api_url),
    })
  },
  //正常的请求
  request: request
}

module.exports = minaApi